package com.itheima.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionMapper;
import com.itheima.dao.RoleMapper;
import com.itheima.dao.UserMapper;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * 类 名: UserServiceImpl
 * 描 述:
 * 作 者: 蔡畅
 * 创 建：2019年12月01日
 */

/**
 * @auhor:caichang
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public User loadUserByUserName(String username) {
        //（移动端套餐详情）要的数据结构和 套餐 -> 检查组 -> 检查项
        //1.根据用户名称查询用户的基本信息(要返回id,username,password)
        User user = userMapper.findByUserName(username);
        if (user != null) {
            //2、根据用户id查询用户的角色集合（t_user t_user_role t_role）
            Set<Role> roles = roleMapper.findByUserId(user.getId());
            if (CollectionUtil.isNotEmpty(roles)) {
                //3.循环角色查询下面的权限(t_role t_role_permission t_permission)
                for (Role role : roles) {
                    Set<Permission> permissions = permissionMapper.findByRoleId(role.getId());
                    role.setPermissions(permissions);
                }
            }
            //一次啊性查出用户所有的权限
            List<String> permissions = permissionMapper.findKeywordByUserId(user.getId());
            user.setRoles(roles);
        }
        return user;
    }
}
